package day65;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import org.junit.Test;

import day11.JDBCUtil;

public class TransactionTest {

	@Test
	public void test1() {
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		String sql1 = "UPDATE account SET money=money-1000 WHERE name='张三'";
		String sql2 = "UPDATE account SET money=money+1000 WHERE name='李四'";
		try {
			connection = JDBCUtil.getConnection();
			
			// 为false，表示禁用自动提交（默认情况是true）
			connection.setAutoCommit(false);
			
			preparedStatement = connection.prepareStatement(sql1);
			System.out.println(preparedStatement);
			preparedStatement.executeUpdate();
			
			// ArithmeticException: / by zero
			int i = 3 / 0;
			
			preparedStatement = connection.prepareStatement(sql2);
			System.out.println(preparedStatement);
			preparedStatement.executeUpdate();
			
			// setAutoCommit(false)改成false之后，不会提交数据库，只有调用connection.commit()才提交
			connection.commit();
		} catch (SQLException e) {
			e.printStackTrace();
			try {
				connection.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		} finally {
			JDBCUtil.close(connection, preparedStatement, null);
		}
		
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
}
